import os
import oss2
import requests
import time
from urllib.parse import urlparse
import hashlib

# OSS配置（请替换为实际的OSS配置）
OSS_ACCESS_KEY_ID = 'your_access_key_id'
OSS_ACCESS_KEY_SECRET = 'your_access_key_secret'
OSS_ENDPOINT = 'https://oss-cn-hangzhou.aliyuncs.com'  # 根据实际区域修改
OSS_BUCKET_NAME = 'huaxianguan-images'

def init_oss():
    """初始化OSS客户端"""
    auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
    bucket = oss2.Bucket(auth, OSS_ENDPOINT, OSS_BUCKET_NAME)
    return bucket

def download_and_upload_image(url, oss_key, bucket):
    """下载图片并上传到OSS"""
    try:
        # 下载图片
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        
        # 上传到OSS
        result = bucket.put_object(oss_key, response.content)
        if result.status == 200:
            oss_url = f"https://{OSS_BUCKET_NAME}.{OSS_ENDPOINT.replace('https://', '')}/{oss_key}"
            print(f"上传成功: {oss_url}")
            return oss_url
        else:
            print(f"上传失败: {result.status}")
            return None
    except Exception as e:
        print(f"处理失败 {url}: {e}")
        return None

def upload_flower_images():
    """上传鲜花图片到OSS"""
    # 初始化OSS
    try:
        bucket = init_oss()
    except Exception as e:
        print(f"OSS初始化失败: {e}")
        print("请先配置正确的OSS参数")
        return {}
    
    # 鲜花图片URL列表
    flower_images = {
        "红玫瑰.jpg": "https://images.unsplash.com/photo-1518895949257-7621c3c786d7?w=800&h=600&fit=crop",
        "粉玫瑰.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "白玫瑰.jpg": "https://images.unsplash.com/photo-1582794543139-8ac9cb0f7b11?w=800&h=600&fit=crop",
        "红康乃馨.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "粉康乃馨.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop",
        "白百合.jpg": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
        "粉百合.jpg": "https://images.unsplash.com/photo-1490750967868-88aa4486c946?w=800&h=600&fit=crop",
        "向日葵.jpg": "https://images.unsplash.com/photo-1470509037663-253afd7f0f51?w=800&h=600&fit=crop",
        "红郁金香.jpg": "https://images.unsplash.com/photo-1520637836862-4d197d17c93a?w=800&h=600&fit=crop",
        "粉郁金香.jpg": "https://images.unsplash.com/photo-1584464491033-06628f3a6b7b?w=800&h=600&fit=crop",
        "满天星.jpg": "https://images.unsplash.com/photo-1563241527-3004b7be0ffd?w=800&h=600&fit=crop"
    }
    
    oss_urls = {}
    
    print("开始上传鲜花图片到OSS...")
    
    for filename, url in flower_images.items():
        oss_key = f"flowers/{filename}"
        oss_url = download_and_upload_image(url, oss_key, bucket)
        if oss_url:
            oss_urls[filename] = oss_url
        
        # 添加延迟避免被限制
        time.sleep(1)
    
    print("图片上传完成！")
    return oss_urls

if __name__ == "__main__":
    # 注意：需要先安装 oss2 库
    # pip install oss2
    
    print("注意：请先在代码中配置正确的OSS参数")
    print("包括：OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, OSS_ENDPOINT, OSS_BUCKET_NAME")
    
    # 如果已配置OSS参数，取消下面的注释
    # oss_urls = upload_flower_images()
    # print("OSS URLs:", oss_urls)